<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Card List</title>
</head>
<style>
  /* 移除ul的默认内边距和边距 */
  ul,
  h1,
  h2,
  h6 {
    padding: 0;
    margin: 0;
    list-style-type: none;
    /* 移除默认的列表项标记 */
  }

  /* 移除li的默认样式 */
  li {
    padding: 0;
    margin: 0;
  }

  body {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    line-height: 1;
    height: 100vh;
    background-color: #F5F5F5;
    font-family: Arial, sans-serif;
  }

  .page-wrapper {
    height: inherit;
    text-align: center;
  }

  .page-container {
    height: fit-content;
    display: none;
    padding: 10px;
  }

  .page-container.active {
    display: block;
  }

  .page-header {
    font-size: 22px;
    color: #FFFFFF;
    height: 60px;
    line-height: 60px;
    /* background-color: #0f61ca; */
    background-color: #3767CE;
    /* background-color: #568afa; */
  }

  .page-footer {
    font-size: 16px;
    font-weight: 800;
    /* color: #0f61ca; */
    color: #3767CE;
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: #faf9f9;
    display: flex;
    justify-content: space-around;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  }

  .page-footer span {
    position: relative;
    padding: 16px;
    width: 100%;
  }

  .page-footer span.active {
    color: #FFFFFF;
    font-weight: 700;
    background-color: #3767CE;
  }

  .card-list {
    height: 100%;
  }

  .card-list-item {
    color: #333333;
    margin-bottom: 20px;
    margin-top: 10px;
    background-color: #FFFFFF;
    border-radius: 10px;
  }

  .card-list-item.active {
    background-color: #568afa;
    color: #FFFFFF;
  }

  .card-header {
    padding: 10px;
    font-size: 18px;
    border-bottom: 1px solid #d3cece;
  }

  .card-header-desc {
    margin: 10px 0;
    font-size: 14px;
    text-align: left;
    color: #637882;
  }

  .card-header-desc-item {
    padding: 2px 0;
  }

  .card-body {
    padding: 10px;
  }

  .card-body-header {
    color: #568afa;
    display: flex;
    justify-content: space-between;
  }

  .card-body-content-description {
    /* color: #637882; */
    color: #000000;
    line-height: 28px;
    font-size: 14px;
  }

  .modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgb(0, 0, 0);
    background-color: rgba(0, 0, 0, 0.4);
    padding-top: 60px;
  }

  .modal-content {
    background-color: #fefefe;
    margin: 5% auto;
    padding: 10px 20px;
    border: 1px solid #888;
    width: 80%;
    max-width: 300px;
    border-radius: 10px;
  }

  .close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
  }

  .close:hover,
  .close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
  }

  .modal-btn {
    width: 30%;
    height: 32px;
    background: #568afa;
    color: #FFFFFF;
    border: none;
    border-radius: 4px;
  }

  .button {
    /* background: linear-gradient(13.card-list-item5deg, #0f61ca, #07CF03); */
    background-color: #2196F3;
    border: none;
    border-radius: 10px;
    color: white;
    padding: 0 10px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    font-weight: 800;
    cursor: pointer;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    transition: 0.3s, transform 0.3s;
  }

  .button:hover {
    background: linear-gradient(135deg, #07CF03, #3767CE);
    transform: translateY(-2px);
  }

  .button:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .line-button {
    width: 60%;
    padding: 10px
  }

  .search-btn {
    /* background: linear-gradient(135deg, #07CF03, #c2ef5a); */
    background-color: #F4E1A4;
    color: brown;
  }

  .fancy-input-label {
    flex: 3;
    text-align: right;
  }

  .fancy-input {
    width: 100%;
    padding: 15px;
    border: none;
    border-radius: 10px;
    background-color: #ffffff;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    font-size: 16px;
    color: #333333;
    transition: border-color 0.3s, box-shadow 0.3s;
  }

  .fancy-input:disabled {
    background-color: #eee;
    color: #999;
    cursor: not-allowed;
  }

  .fancy-input:focus {
    outline: none;
    border-color: #07CF03;
    box-shadow: 0 4px 6px rgba(0, 127, 100, 0.3);
  }

  .form-item-group {
    display: flex;
    align-items: center;
    margin: 20px 0;
    gap: 40px;
    justify-content: center;
  }

  .form-item-group-2 {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 4px;
  }

  .from-item-group-3 {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 95%;
    justify-content: space-around;
    margin: 12px 0 10px 0;
  }


  .form-item-group-2 label {
    flex: 1;
    text-align: right;
    margin-right: 10px;
    line-height: 20px;
  }

  .fancy-input,
  .select-container {
    flex: 3;
    display: flex;
    margin-right: 10px;
    gap: 10px;
  }

  .from-item-button {
    margin: 12px 0 0 0;
    width: 80px;
    min-height: 40px;
    margin-top: 0px;
  }

  .custom-select {
    position: relative;
    display: inline-block;
    width: 100%;
    padding: 15px;
    border: none;
    border-radius: 10px;
    background-color: #ffffff;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    font-size: 16px;
    color: #333333;
    transition: border-color 0.3s, box-shadow 0.3s;
    -webkit-appearance: none;
    -moz-appearance: none;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 5"><path fill="#333" d="M2 0L0 2h4z"/></svg>');
    background-repeat: no-repeat;
    background-position: right 10px center;
    background-size: 10px 6px;
    cursor: pointer;
  }

  .custom-select:focus {
    outline: none;
    border-color: #568afa;
    box-shadow: 0 4px 6px rgba(0, 127, 100, 0.3);
  }

  .custom-select option {
    padding: 10px;
    color: #333333;
    background-color: #ffffff;
  }

  /* 隐藏默认的复选框 */
  .fancy-checkbox {
    display: none;
  }

  /* 自定义复选框的容器 */
  .fancy-checkbox+label {
    position: relative;
    padding-left: 28px;
    cursor: pointer;
    user-select: none;
    margin-bottom: 10px;
    line-height: 20px;
  }

  /* 自定义复选框的外观 */
  .fancy-checkbox+label::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 20px;
    height: 20px;
    background-color: #FFFFFF;
    border: 1px solid #ccc;
    border-radius: 4px;
    transition: background-color 0.3s, border-color 0.3s;
  }

  /* 选中状态下的复选框外观 */
  .fancy-checkbox:checked+label::before {
    background-color: #2196F3;
    border-color: #2196F3;
  }

  /* 选中状态下复选框内的勾 */
  .fancy-checkbox:checked+label::after {
    content: '';
    position: absolute;
    left: 8px;
    top: 2px;
    width: 5px;
    height: 10px;
    border: solid white;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
  }

  .fancy-radio {
    display: none;
  }

  .fancy-radio+label {
    position: relative;
    padding-left: 25px;
    cursor: pointer;
    user-select: none;
    margin-bottom: 10px;
  }

  .fancy-radio+label::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 20px;
    height: 20px;
    background-color: #eee;
    border-radius: 50%;
    transition: background-color 0.3s;
  }

  .fancy-radio:checked+label::before {
    background-color: #2196F3;
  }

  .fancy-radio:checked+label::after {
    content: '';
    position: absolute;
    left: 6px;
    top: 6px;
    width: 8px;
    height: 8px;
    background-color: white;
    border-radius: 50%;
  }

  .form-button-group {
    display: flex;
    width: 80%;
    justify-content: space-between;
    margin: 20px auto;
    gap: 12px;
  }

  .system-card {
    margin: 0 auto;
    ;
    background-color: #FFFFFF;
  }

  .start-button {
    width: 100%;
    padding: 16px 0;
    background: #2196F3;
    color: #FFFFFF;
    border-radius: 18px;
    font-weight: 700;
    font-size: 16px;
  }

  .start-button-false {
    background-color: #F4E1A4;
    color: brown;
  }

  .calibration-input {}

  .calibration-btn {
    background-color: #3767ce;
  }

  .wifi-list {
    background-color: antiquewhite;
    border-radius: 4px;
    animation: slide-up 0.3s ease-in-out;
    z-index: 9999;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  .wifi-list-item {
    padding: 10px;
    text-align: left;
    border-bottom: 1px solid #e6dede;
  }

  @keyframes slide-up {
    from {
      transform: translateY(100%);
    }

    to {
      transform: translateY(0);
    }
  }
</style>

<body>
  <div class="page-wrapper">
    <h1 class="page-header">
      电子器件在线测试平台
    </h1>

    <!-- 页面1 -->
    <div class="page-container active" id="page-1">
      <ul class="card-list" id="card-list">
      </ul>
      <div class="page-container-end">
        到底了~
      </div>
    </div>

    <!-- 页面2 -->
    <div class="page-container" id="page-2">
      <div>
        <div class="form-item-group">
          <input class="fancy-checkbox" type="checkbox" id="STA" onchange="updateInputs()">
          <label for="STA">STA模式</label>
          <input class="fancy-checkbox" type="checkbox" id="AP" onchange="updateInputs()">
          <label for="AP">AP模式</label>
        </div>
        <div class="form-item-group-2">
          <label for="">WIFI名称</label>
          <input class="fancy-input" type="text" id="wifi-name">
        </div>
        <div class="form-item-group-2">
          <label for="">WIFI密码</label>
          <input class="fancy-input" type="text" id="wifi-password">
        </div>
      </div>
      <div class="form-button-group">
        <button class="button line-button search-btn" onclick="getWifiList()">查 询</button>
        <button class="button line-button" onclick="onSubmit()">保 存</button>
      </div>

      <div class="wifi-search-result">
        <ul id="wifi-list" class="wifi-list">
        </ul>
      </div>
    </div>

    <!-- 页面3 -->
    <div class="page-container" id="page-3">
      <ul class="card-list">
        <li class="card-list-item system-card">
          <div class="card-header">
            <h2>ADC校准</h2>
            <div class="card-header-desc">
              <p class="card-header-desc-item">1. 在校准前，请先把载板与主控板分离。</p>
              <p class="card-header-desc-item">2. 点击开始校准后, VDD、VDDIO将分别输出约3.3V。</p>
              <p class="card-header-desc-item">3. 请把对应的测量电压值填入下列表格中。</p>
            </div>
          </div>
          <div class="card-body">
            <p class="start-button" id="start-button-true" onclick="onStarCalibrationADC(true)"> 开 始 校 准 </p>
            <p class="start-button start-button-false" id="start-button-false" onclick="onStarCalibrationADC(false)"
              style="display: none;"> 正 在 校 准 </p>
            <div class="from-item-group-3">
              <label for="" class="fancy-input-label">VDD电压</label>
              <input class="fancy-input calibration-input" type="number" oninput="validateInput(this)">
              <button class="button from-item-button calibration-btn"
                onclick="onCalibration('calibrationVDD')">确定</button>
            </div>
            <div class="from-item-group-3">
              <label for="" class="fancy-input-label">VDDIO电压</label>
              <input class="fancy-input calibration-input" type="number" oninput="validateInput(this)">
              <button class="button from-item-button calibration-btn"
                onclick="onCalibration('calibrationVDDIO')">确定</button>
            </div>
            <div class="from-item-group-3">
              <label for="" class="fancy-input-label">锂电池电压</label>
              <input class="fancy-input calibration-input" type="number" oninput="validateInput(this)">
              <button class="button from-item-button calibration-btn"
                onclick="onCalibration('calibrationBBATT')">确定</button>
            </div>
          </div>
        </li>
      </ul>
    </div>

    <div class="page-footer">
      <span class="page-menu active" data-menu="1" onclick="onChangePage('1')">主页</span>
      <span class="page-menu" data-menu="2" onclick="onChangePage('2')">网络设置</span>
      <span class="page-menu" data-menu="3" onclick="onChangePage('3')">系统设置</span>
    </div>

    <div id="confirmModal" class="modal">
      <div class="modal-content">
        <span class="close" onclick="onClose()">&times;</span>
        <p id="modal-msg"></p>
        <button class="modal-btn" id="confirmYes" onclick="onOk()">确定</button>
      </div>
    </div>

  </div>
</body>
<script>
  const pageMenus = document.querySelectorAll('.page-menu');
  const pageContainers = document.querySelectorAll('.page-container');
  const staCheckbox = document.getElementById('STA');
  const apCheckbox = document.getElementById('AP');
  const wifiNameInput = document.getElementById('wifi-name');
  const wifiPasswordInput = document.getElementById('wifi-password');

  /************************Common******************************************************/
  function onChangePage(pageNumber) {
    highlightPage(pageNumber);
    showPageContent(pageNumber);
  }

  function highlightPage(pageNumber) {
    pageMenus.forEach(menu => menu.classList.remove('active'));
    const activePage = document.querySelector(`.page-menu[data-menu="${pageNumber}"]`);
    if (activePage) {
      activePage.classList.add('active');
    }
  }

  function showPageContent(pageNumber) {
    pageContainers.forEach(container => container.classList.remove('active'));
    const activeContainer = document.getElementById(`page-${pageNumber}`);
    if (activeContainer) {
      activeContainer.classList.add('active');
    }
  }
  /***********************Page1*******************************************************/
  let willActiveCard = null, activeCardIndex = 0;

  function onActive(card, index) {
    // 记录当前点击的卡片
    willActiveCard = card;
    activeCardIndex = index;
    if (willActiveCard.classList.contains('active')) {
      return;
    }
    document.getElementById('confirmModal').style.display = 'block';
    document.getElementById('modal-msg').textContent = `您确定要切换卡片到「${willActiveCard.querySelector('.card-header').textContent}」吗?`;
  }

  function onOk() {
    const formData = new FormData();
    formData.append('select', activeCardIndex);
    // 当用户确认时，发送对应的卡片编号{"select":0}，当返回{"R_select":0}时对应卡片才会切换为选中颜色
    fetch('/switchFunctionList', {
      method: 'POST', // 显式指定请求方法
      body: formData // 发送表单数据
    })
      .then(response => {
        if (!response || !response.ok) {
          throw new Error(`HTTP 错误！状态: ${response ? response.status : '未知'}`);
        }
        return response.json();
      })
      .then(data => {
        if (data.R_select === activeCardIndex) {
          // 移除所有卡片的激活状态
          const cards = document.querySelectorAll('.card-list-item');
          cards.forEach(c => c.classList.remove('active'));
          // 激活当前点击的卡片
          willActiveCard.classList.add('active');

        } else {
          console.error(`切换失败当前要切换:  ${activeCardIndex} ,返回的是 ${data.R_select}`);
        }
      })
      .catch(err => {
        console.error('切换卡片接口失败:', err);
      })
      .finally(() => {
        this.onClose();
        activeCardIndex = 0
        willActiveCard = null;
      });
  }

  function onClose() {
    console.log('onChange')
    document.getElementById('confirmModal').style.display = 'none';
  }

  // 当用户点击模态框外部时，关闭模态框
  window.onclick = function (event) {
    var modal = document.getElementById('confirmModal');
    if (event.target == modal) {
      modal.style.display = 'none';
    }
  };

  function getFunctionList() {
    fetch('/getFunctionList', { "getFunctionList": true })
      .then(response => {
        if (!response || !response.ok) {
          throw new Error(`HTTP 错误！状态: ${response ? response.status : '未知'}`);
        }
        return response.json();
      })
      .then(data => {
        const cardList = document.getElementById('card-list');
        data.functions.forEach((functionData, index) => {
          createCardItem(cardList, functionData, index === data.selected, index);
        });
      })
      .catch(err => {
        console.error('获取功能列表时出错:', err);
      });
  }


  function createCardItem(cardList, functionData, isActive, index) {
    const li = document.createElement('li');
    li.className = 'card-list-item';
    if (isActive) {
      li.classList.add('active');
    }

    const cardHeader = document.createElement('div');
    cardHeader.className = 'card-header';
    cardHeader.textContent = functionData.name;

    const cardBody = document.createElement('div');
    cardBody.className = 'card-body';

    const cardBodyHeader = document.createElement('div');
    cardBodyHeader.className = 'card-body-header';

    const cardBodyContent = document.createElement('div');
    cardBodyContent.className = 'card-body-content';

    const cardBodyContentDescription = document.createElement('div');
    cardBodyContentDescription.className = 'card-body-content-description';
    cardBodyContentDescription.textContent = functionData.explain;

    const cardBodyFooter = document.createElement('div');
    cardBodyFooter.className = 'card-body-footer';

    cardBodyContent.appendChild(cardBodyContentDescription);
    cardBody.appendChild(cardBodyHeader);
    cardBody.appendChild(cardBodyContent);
    cardBody.appendChild(cardBodyFooter);
    li.appendChild(cardHeader);
    li.appendChild(cardBody);

    li.addEventListener('click', () => onActive(li, index));
    cardList.appendChild(li);
  }

  getFunctionList();
  updateInputs();

  /***********************Page2*******************************************************/
  function updateInputs() {
    if (staCheckbox.checked) {
      wifiNameInput.disabled = false;
      wifiPasswordInput.disabled = false;
    } else {
      wifiNameInput.disabled = true;
      wifiPasswordInput.disabled = true;
    }
  };

  function getWifiInfo() {
    fetch('/getWifiInfo', { "getWifiMode": true })
      .then(response => {
        if (!response) {
          throw new Error(`HTTP 错误！状态: ${response ? response.status : '未知'}`);
        }
        return response.json();
      })
      .then(data => {
        if (data.R_getWifiMode === 'STA') {
          staCheckbox.checked = true;
        } else if (data.R_getWifiMode === 'AP') {
          apCheckbox.checked = true;
        } else {
          staCheckbox.checked = true;
          apCheckbox.checked = true;
        }
        if (data.R_ssid) {
          wifiNameInput.value = data.R_ssid;
        }
        if (data.R_pwd) {
          wifiNameInput.value = data.R_pwd;
        }
        updateInputs();
      })
  }

  function onSubmit() {
    let wifiMode = '';

    if (staCheckbox.checked && apCheckbox.checked) {
      wifiMode = 'APSTA';
    } else if (staCheckbox.checked) {
      wifiMode = 'STA';
    } else if (apCheckbox.checked) {
      wifiMode = 'AP';
    }

    const formData = new FormData();
    formData.append('wifiMode', wifiMode);
    formData.append('ssid', wifiNameInput.value,);
    formData.append('password',  wifiPasswordInput.value);
    fetch('/saveWifi', {
      method: 'POST', // 显式指定请求方法
      body: formData
    })

      .then(response => response.json())
      .then(data => {
        alert("设置成功");
      })
      .catch(error => {
        console.error("Error:", error);
      });
  }

  function getWifiList() {
    fetch('/getWifiList')
      .then(response => {
        if (!response) {
          throw new Error(`HTTP 错误！状态: ${response ? response.status : '未知'}`);
        }
        return response.json();
      })
      .then(data => {
        if (data.R_wifiList.length > 0) {
          const wifiList = document.getElementById('wifi-list');
          data.R_wifiList.forEach((item, index) => {
            const li = document.createElement('li');
            li.className = 'wifi-list-item';
            li.textContent = item.ssid;
            li.addEventListener('click', function () {
              wifiNameInput.value = item.ssid;
            });
            wifiList.appendChild(li);
          })
        }
      })
  }
  /***********************Page3*******************************************************/

  function validateInput(input) {
    const value = input.value;
    // 检查输入是否为空或不是数字
    if (value === "" || isNaN(value)) {
      // 如果为空或不是数字，则重置输入框
      input.value = "";
      return;
    }
    const number = parseFloat(value);
    if (number <= 0) {
      input.value = "";
    }
  }

  function onStarCalibrationADC(status) {
    const formData = new FormData();
    formData.append('starCalibrationADC', status); 
    fetch('/starCalibrationADC', {
      method: 'POST', // 显式指定请求方法
      body: formData // 将参数序列化到body
    })
      .then(response => {
        if (!response) {
          throw new Error(`HTTP 错误！状态: ${response ? response.status : '未知'}`);
        }
        return response.json();
      })
      .then(data => {
        if (data.R_starCalibrationADC) {
          document.getElementById('start-button-true').style.display = 'none';
          document.getElementById('start-button-false').style.display = 'block';
          var inputs = document.querySelectorAll('.calibration-input, .calibration-btn');

          // 遍历所有元素并禁用它们
          inputs.forEach(function (element) {
            element.disabled = false;
          });
        } else {
          document.getElementById('start-button-false').style.display = 'none';
          document.getElementById('start-button-true').style.display = 'block';
          var inputs = document.querySelectorAll('.calibration-input, .calibration-btn');
          inputs.forEach(function (element) {
            element.disabled = true;
          });
        }
      })
      .catch(err => {
        isCalibrating = false;
      });
  }

  function onCalibration(type) {
    const formData = new FormData();
    formData.append(type, true); 
    fetch('/calibration', {
      method: 'POST', // 显式指定请求方法
      body: formData // 将参数序列化到body
    })
      .then(response => {
        if (!response) {
          throw new Error(`HTTP 错误！状态: ${response ? response.status : '未知'}`);
        }
        return response.json();
      })
      .then(data => {
        if (data[`R_${type}`]) {
          alert(`${type} 成功`);
        }
      })
      .catch(err => {

      });
  }

</script>

</html>